<template>
  <div class="account-info">
    <div class="account-header">
      <h3>👤 账户信息</h3>
      <p>管理您的个人账户和偏好设置</p>
    </div>

    <div class="account-content">
      <!-- 用户信息卡片 -->
      <div class="user-card">
        <div class="user-avatar">
          <div class="avatar-placeholder">
            {{ userInitials }}
          </div>
        </div>
        
        <div class="user-details">
          <h4>{{ userInfo.name || '未设置用户名' }}</h4>
          <p class="user-email">{{ userInfo.email || '未设置邮箱' }}</p>
          <p class="user-role">{{ userInfo.role || '标准用户' }}</p>
        </div>
        
        <div class="user-stats">
          <div class="stat-item">
            <span class="stat-number">{{ userStats.savedMaterials || 0 }}</span>
            <span class="stat-label">保存的分子</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ userStats.searchCount || 0 }}</span>
            <span class="stat-label">搜索次数</span>
          </div>
        </div>
      </div>

      <!-- 账户设置 -->
      <div class="settings-section">
        <h4>账户设置</h4>
        
        <div class="settings-group">
          <div class="setting-item">
            <label>用户名</label>
            <input
              v-model="userInfo.name"
              placeholder="输入用户名"
              @blur="saveSettings"
            />
          </div>
          
          <div class="setting-item">
            <label>邮箱地址</label>
            <input
              v-model="userInfo.email"
              type="email"
              placeholder="输入邮箱地址"
              @blur="saveSettings"
            />
          </div>
          
          <div class="setting-item">
            <label>主题偏好</label>
            <select v-model="userSettings.theme" @change="saveSettings">
              <option value="light">浅色主题</option>
              <option value="dark">深色主题</option>
              <option value="auto">跟随系统</option>
            </select>
          </div>
          
          <div class="setting-item">
            <label>语言设置</label>
            <select v-model="userSettings.language" @change="saveSettings">
              <option value="zh-CN">中文</option>
              <option value="en-US">English</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 使用统计 -->
      <div class="usage-stats">
        <h4>使用统计</h4>
        
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">🔍</div>
            <div class="stat-info">
              <span class="stat-value">{{ userStats.totalSearches || 0 }}</span>
              <span class="stat-title">总搜索次数</span>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">💾</div>
            <div class="stat-info">
              <span class="stat-value">{{ userStats.savedFiles || 0 }}</span>
              <span class="stat-title">保存的文件</span>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">🤖</div>
            <div class="stat-info">
              <span class="stat-value">{{ userStats.aiChats || 0 }}</span>
              <span class="stat-title">AI对话</span>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">📅</div>
            <div class="stat-info">
              <span class="stat-value">{{ formatJoinDate }}</span>
              <span class="stat-title">加入日期</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 账户操作 -->
      <div class="account-actions">
        <h4>账户操作</h4>
        
        <div class="action-buttons">
          <button class="action-btn primary" @click="exportData">
            📤 导出所有数据
          </button>
          
          <button class="action-btn secondary" @click="clearHistory">
            🗑️ 清除搜索历史
          </button>
          
          <button class="action-btn danger" @click="resetSettings">
            🔄 重置设置
          </button>
        </div>
      </div>

      <!-- 系统信息 -->
      <div class="system-info">
        <h4>系统信息</h4>
        
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">应用版本</span>
            <span class="info-value">v1.0.0</span>
          </div>
          
          <div class="info-item">
            <span class="info-label">最后登录</span>
            <span class="info-value">{{ formatLastLogin }}</span>
          </div>
          
          <div class="info-item">
            <span class="info-label">存储使用</span>
            <span class="info-value">{{ storageUsage }}</span>
          </div>
          
          <div class="info-item">
            <span class="info-label">用户ID</span>
            <span class="info-value">{{ userInfo.id || 'N/A' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 状态提示 -->
    <div v-if="statusMessage" :class="['status-message', statusType]">
      {{ statusMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const userInfo = ref({
  name: '',
  email: '',
  role: '标准用户',
  id: 'user_' + Math.random().toString(36).substr(2, 9),
  joinDate: new Date().toISOString(),
  lastLogin: new Date().toISOString()
})

const userSettings = ref({
  theme: 'light',
  language: 'zh-CN',
  notifications: true,
  autoSave: true
})

const userStats = ref({
  savedMaterials: 0,
  searchCount: 0,
  totalSearches: 0,
  savedFiles: 0,
  aiChats: 0
})

const statusMessage = ref('')
const statusType = ref('info')

const userInitials = computed(() => {
  if (userInfo.value.name) {
    return userInfo.value.name.split(' ').map(n => n[0]).join('').toUpperCase()
  }
  return 'U'
})

const formatJoinDate = computed(() => {
  if (userInfo.value.joinDate) {
    return new Date(userInfo.value.joinDate).toLocaleDateString('zh-CN')
  }
  return '未知'
})

const formatLastLogin = computed(() => {
  if (userInfo.value.lastLogin) {
    return new Date(userInfo.value.lastLogin).toLocaleString('zh-CN')
  }
  return '从未登录'
})

const storageUsage = computed(() => {
  // 模拟存储使用计算
  const used = Math.floor(Math.random() * 50) + 10
  return `${used} MB / 100 MB`
})

const showStatus = (message, type = 'info') => {
  statusMessage.value = message
  statusType.value = type
  setTimeout(() => {
    statusMessage.value = ''
  }, 3000)
}

const saveSettings = () => {
  try {
    localStorage.setItem('userSettings', JSON.stringify(userSettings.value))
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    showStatus('设置已保存', 'success')
  } catch (error) {
    console.error('保存设置失败:', error)
    showStatus('保存失败', 'error')
  }
}

const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('userSettings')
    const savedInfo = localStorage.getItem('userInfo')
    const savedStats = localStorage.getItem('userStats')
    
    if (savedSettings) {
      userSettings.value = JSON.parse(savedSettings)
    }
    
    if (savedInfo) {
      userInfo.value = { ...userInfo.value, ...JSON.parse(savedInfo) }
    }
    
    if (savedStats) {
      userStats.value = JSON.parse(savedStats)
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

const exportData = () => {
  const dataToExport = {
    userInfo: userInfo.value,
    userSettings: userSettings.value,
    userStats: userStats.value,
    exportDate: new Date().toISOString()
  }
  
  try {
    const jsonData = JSON.stringify(dataToExport, null, 2)
    const blob = new Blob([jsonData], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `molecule-scope-backup-${new Date().getTime()}.json`
    link.click()
    
    URL.revokeObjectURL(url)
    showStatus('数据导出成功', 'success')
  } catch (error) {
    console.error('导出失败:', error)
    showStatus('导出失败', 'error')
  }
}

const clearHistory = () => {
  if (confirm('确定要清除所有搜索历史吗？此操作不可撤销。')) {
    userStats.value.searchCount = 0
    userStats.value.totalSearches = 0
    localStorage.setItem('userStats', JSON.stringify(userStats.value))
    localStorage.removeItem('recentSearches')
    showStatus('搜索历史已清除', 'success')
  }
}

const resetSettings = () => {
  if (confirm('确定要重置所有设置为默认值吗？')) {
    userSettings.value = {
      theme: 'light',
      language: 'zh-CN',
      notifications: true,
      autoSave: true
    }
    saveSettings()
    showStatus('设置已重置', 'success')
  }
}

// 初始化加载设置
onMounted(() => {
  loadSettings()
  // 更新最后登录时间
  userInfo.value.lastLogin = new Date().toISOString()
  saveSettings()
})
</script>

<style scoped>
.account-info {
  height: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 0;
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.account-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.account-header h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.account-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.account-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  margin-bottom: 30px;
}

.user-avatar {
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

.user-details {
  flex: 1;
}

.user-details h4 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.user-email {
  margin: 0 0 4px 0;
  opacity: 0.9;
  font-size: 14px;
}

.user-role {
  margin: 0;
  opacity: 0.8;
  font-size: 12px;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 12px;
  display: inline-block;
}

.user-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
}

.settings-section,
.usage-stats,
.account-actions,
.system-info {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.settings-section h4,
.usage-stats h4,
.account-actions h4,
.system-info h4 {
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.settings-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.setting-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.setting-item label {
  font-weight: 500;
  color: #495057;
  font-size: 14px;
}

.setting-item input,
.setting-item select {
  padding: 10px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.setting-item input:focus,
.setting-item select:focus {
  border-color: #007bff;
  outline: none;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 24px;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
}

.stat-title {
  font-size: 12px;
  color: #6c757d;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.primary {
  background: #007bff;
  color: white;
}

.action-btn.primary:hover {
  background: #0056b3;
}

.action-btn.secondary {
  background: #6c757d;
  color: white;
}

.action-btn.secondary:hover {
  background: #545b62;
}

.action-btn.danger {
  background: #dc3545;
  color: white;
}

.action-btn.danger:hover {
  background: #c82333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: white;
  border-radius: 6px;
}

.info-label {
  font-weight: 500;
  color: #495057;
  font-size: 14px;
}

.info-value {
  color: #6c757d;
  font-size: 14px;
  font-family: monospace;
}

.status-message {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  z-index: 1000;
}

.status-message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-message.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

@media (max-width: 768px) {
  .user-card {
    flex-direction: column;
    text-align: center;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .stats-grid {
    grid-template-columns: 1fr 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>